package com.feng.study.demo;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * 本地缓存Cache
 * package com.google.common.cache;
 * guava
 */
@Slf4j
public class CacheDemo {
    private final static Cache<Integer, Integer> INTEGER_CACHE = CacheBuilder.newBuilder()
            .initialCapacity(1).maximumSize(1).expireAfterWrite(10, TimeUnit.SECONDS).build();

    public static void main(String[] args) {
        testGet01();
    }

    /**
     * get()方法，当对于get++put
     */
    private static void testGet01(){
        try {
            Integer integer = INTEGER_CACHE.get(1, new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return 19;
                }
            });
            System.out.println(integer);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    private void testGet02(){
        try {
            Integer integer = INTEGER_CACHE.get(1, this::getValue);
            System.out.println(integer);
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private Integer getValue(){
        //获取值
        return 20;
    }
}
